package com.sprite.utils.http;

import com.sprite.utils.UtilString;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jack
 */
public class UrlParams extends HashMap<String, Object> {

    /**
     *
     */
    private static final long serialVersionUID = -6016715899215393800L;

    private String charset;

    public String getCharset() {
        return charset;
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    /**
     * 转成query string
     *
     * @return Query String
     * @since 1.2.4
     */
    public String toQueryString() throws UnsupportedEncodingException {
        if (isEmpty()) {
            return "";
        }

        String paramCharset = charset != null ? charset : Charset.defaultCharset().name();

        StringBuilder finalUrl = new StringBuilder();
        for (Map.Entry<String, Object> param : entrySet()) {
            finalUrl.append(param.getKey()).append("=").append(URLEncoder.encode(UtilString.toString(param.getValue()), paramCharset)).append("&");
        }
        finalUrl.deleteCharAt(finalUrl.length() - 1);

        return finalUrl.toString();
    }

    /**
     * 将url param 追加到url上
     *
     * @param url
     *         url
     * @return Query String
     */
    public String appendToUrl(String url) throws UnsupportedEncodingException{
        if (isEmpty()) {
            return url;
        }

        StringBuilder finalUrl = new StringBuilder(url);
        String paramCharset = charset != null ? charset : Charset.defaultCharset().name();
        int i;
        if ((i = url.lastIndexOf('?')) < 0) {
            finalUrl.append("?");
        } else if (i > 0 && !url.endsWith("&")) {
            finalUrl.append('&');
        }
        for (Map.Entry<String, Object> param : entrySet()) {
            finalUrl.append(param.getKey()).append("=").append(URLEncoder.encode(UtilString.toString(param.getValue()), paramCharset)).append("&");
        }
        finalUrl.deleteCharAt(finalUrl.length() - 1);

        return finalUrl.toString();

    }
}
